"""
@author : linrh
@homepage : https://gitee.com/linrh-DUT
@version: 1.0.0
@when : 2023/5/25
@file: thesis_frame.py
"""
import os
import time
import tkinter as tk
from tkinter import filedialog
import tkinter.ttk as ttk

import utils
import threading
import db_util
class ThesisFrame():
    def __init__(self, root):
        self.thesis_tab = root
        self.init_table()
        self.init_btns()
        self.query_time = time.time()

        # 数据库
        db = db_util.get_db()
        self.dict_en2zh_collection = db_util.get_collection(db, 'dict_en2zh')
        self.en_words_collection = db_util.get_collection(db, 'en_words')
        self.reload_words()

    def reload_words(self):
        self.words = [item['word'] for item in db_util.find_all(self.en_words_collection)]
        self.words_mastered = [item['word'] for item in db_util.find_all(self.en_words_collection, {'master': True})]

    def init_table(self):
        # 表格定义
        self.table = ttk.Treeview(self.thesis_tab, show='headings', height=20, columns=('word', 'meaning', 'mastered', 'frequency', 'use_rate'))
        self.table.pack(fill='both', expand='yes', padx=10, pady=10)
        self.table.bind("<<TreeviewSelect>>", self.word_select)
        self.table.bind("<Double-1>", self.word_detail)
        # 表头名称
        self.table.heading(column='word', text='单词', anchor=tk.CENTER)
        self.table.heading(column='meaning', text='释义', anchor=tk.CENTER)
        self.table.heading(column='mastered', text='已学', anchor=tk.CENTER)
        self.table.heading(column='frequency', text='词频', anchor=tk.CENTER)
        self.table.heading(column='use_rate', text='频率', anchor=tk.CENTER)
        # 表头宽度
        self.table.column("word", width=50, anchor=tk.W)
        self.table.column("meaning", width=100, anchor=tk.CENTER)
        self.table.column("mastered", width=20, anchor=tk.CENTER)
        self.table.column("frequency", width=20, anchor=tk.CENTER)
        self.table.column("use_rate", width=20, anchor=tk.CENTER)


    def init_btns(self):
        # 底部Frame
        bottom_frame = tk.Frame(self.thesis_tab)
        bottom_frame.pack(side=tk.BOTTOM, fill=tk.X, padx=10, pady=10)
        # 标签
        self.thesis_label = tk.Label(bottom_frame, text='导入论文后，即可统计论文中的单词。', wraplength=400)
        self.thesis_label.pack(side=tk.TOP)
        # 按钮Frame
        btn_frame = tk.Frame(bottom_frame)
        btn_frame.pack(side=tk.BOTTOM, fill=tk.X)
        # 添加按钮
        btn = tk.Button(btn_frame, text='导入论文', width=5, height=2, command=self.load_file)
        btn.grid(row=0, column=0)

        self.add_master_btn = tk.Button(btn_frame, text='添加已学习', width=5, height=2, command=self.record_master_word, state=tk.DISABLED)
        self.add_master_btn.grid(row=0, column=1)

        self.filter_btn = tk.Button(btn_frame, text='过滤已学', width=5, height=2, command=self.filter_master_word)
        self.filter_btn.grid(row=0, column=2)

    def load_file(self):
        """
        导入论文
        :return:
        """
        filepath = filedialog.askopenfilename()
        if len(filepath) > 0:
            txt = utils.pdf2txt(filepath)
            txt = utils.clear_txt(txt)
            words = utils.words_statistics(txt)
            for item in self.table.get_children():
                self.table.delete(item)
            iids = []
            unkonwn_words = []
            for word, frequency, user_rate in words:
                dict_word = db_util.find_one(self.dict_en2zh_collection, {'word': word})
                # 判断单词是否已经存在，不存在则插入
                if word not in self.words:
                    db_util.insert_one(self.en_words_collection, {'word': word})
                    mastered = '否'
                else:
                    if word in self.words_mastered:
                        mastered = '是'
                    else:
                        mastered = '否'

                if dict_word is not None:
                    meaning = ' '.join(dict_word['translation'])
                    self.table.insert('', tk.END, values=(word, meaning, mastered, frequency, user_rate))
                else:
                    meaning = '正在查询...'
                    iid = self.table.insert('', tk.END, values=(word, meaning, mastered, frequency, user_rate))
                    iids.append(iid)
                    unkonwn_words.append(word)

            threading.Thread(target=self.query_word, args=(unkonwn_words, iids)).start()

            self.thesis_label.config(text=os.path.basename(filepath))
            self.filter_btn.config(state=tk.NORMAL)

    def word_select(self, event):
        """
        单词选择
        :param event:
        :return:
        """
        widgetObj = event.widget
        itemselected = widgetObj.selection()
        self.itemselected = itemselected
        if len(itemselected) > 0:
            self.add_master_btn.config(state=tk.NORMAL)
        else:
            self.add_master_btn.config(state=tk.DISABLED)

    def record_master_word(self):
        """
        记录掌握的单词
        :return:
        """
        for iid in self.itemselected:
            word = self.table.item(iid, "values")[0]  # 获取单词
            db_util.update_one(self.en_words_collection, {'word': word}, {'$set': {'master': True}})
            self.table.delete(iid)
        self.reload_words()

    def filter_master_word(self):
        master_words = [item for item in self.words_mastered]
        for row in self.table.get_children(''):
            word = self.table.item(row, "values")[0]
            if word in master_words:
                self.table.delete(row)
                self.filter_btn.config(state=tk.DISABLED)

    def query_word(self, words, iids):
        print('YOUDAO_开始查询')
        for word, iid in zip(words, iids):
            # 查询
            print(word)
            meaning = utils.yd_query(word)
            self.table.item(iid, values=(word, meaning, self.table.item(iid, "values")[2], self.table.item(iid, "values")[3]))
            time.sleep(1)
        print('YOUDAO_查询结束')
        self.reload_words()

    def word_detail(self, event):
        """
        单词详情
        :param event:
        :return:
        """
        widgetObj = event.widget
        iid = widgetObj.selection()
        requery_time = time.time() - self.query_time
        if len(iid) > 0 and requery_time > 0.1:
            word = self.table.item(iid[0], "values")[0]
            word_detail = db_util.find_one(self.dict_en2zh_collection, {'word': word})
            msg = ''
            if 'explains' in word_detail and len(word_detail['explains']) > 0:
                msg += '释义：\n'
                msg += '\n'.join(word_detail['explains'])
            if 'web' in word_detail and len(word_detail['web']) > 0:
                msg += '\n\n网络释义：'
                for item in word_detail['web']:
                    msg += '\n' + item['key'] + '：' + ','.join(item['value'])
            tk.messagebox.showinfo(title='信息提示！', message=msg)
            self.query_time = time.time()
